import { autorun } from "mobx";
import { ReactNode, useEffect, useRef, useState } from "react";
import styles from "./toolReplaceImg.module.less";
import { Button } from "antd";
import utils from "@/utils/utils";
import utilsServer from "@/api/services/utilsServer";
import editorStore from "@/editorComponent/editorStore";
import designEditor from "@/editorComponent/designEditor";
import FabricImage from "@/myFabric/FabricImage";
import clsx from "clsx";

interface Iprops {
  children?: ReactNode
}

// 替换图片
export default function ToolReplaceImg() {

  const dom = useRef<HTMLDivElement | null>(null);
  const [visible, setVisible] = useState(false);
  const [disable, setDisable] = useState(false);

  useEffect(() => autorun(() => {
    const { activeObjectId, lock } = editorStore;
    setDisable(lock);
    const activeObject = designEditor.fabricCanvas.getActiveObject();
    if (activeObjectId && activeObject && activeObject.type === "image") {
      setVisible(true);
    } else {
      setVisible(false);
    }
  }, { delay: 10 }), []);

  const replaceImg = async () => {
    const file = await utils.selectFile();
    if (file) {
      const src = await utilsServer.uploadOss(file);
      if (src) {
        const activeObject = designEditor.fabricCanvas.getActiveObject();
        if (activeObject && activeObject.type === "image") {
          const originWidth = (activeObject as FabricImage).getScaledWidth();
          (activeObject as FabricImage).setSrc(utils.ossSuffix(src, 1000), () => {
            const scale = originWidth / (activeObject as FabricImage).width!;
            (activeObject as FabricImage).set({
              scaleX: scale,
              scaleY: scale
            });
            designEditor.render();
          });
        }
      }
    }
  }

  return (
    <Button
      block
      className={clsx(styles.toolReplaceImg, visible && styles.visible, disable && styles.disable)}
      onClick={replaceImg}
    >替换图片</Button>
  );

}